<template>
    <div style="width:100%;height: 100%;">
        <div class="appp" id="gobal" ref="app"></div>
        <div class="tag" id="tag" style="display: none;"></div>
        <div class="message" id="message" style="display: none;">
            1233
            <!-- <div @click="close()" style="color: #fff;">123</div> -->
        </div>
        <div class="switch">
            <div v-for="item, index in list" style="display: flex;justify-content: space-between;align-items: center;">
                <div>{{ item.label }}</div>
                <el-switch v-model="item.value" size="large" @change="changeswitch(index)" />
            </div>
        </div>
    </div>
</template>
<style>
#tag {
    width: 70px;
    height: 40px;
    line-height: 32px;
    text-align: center;
    color: #fff;
    font-size: 16px;
    background-image: url("../assets/标签箭头背景.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

#message {
    width: 10px;
    height: 10px;
    line-height: 3px;
    text-align: center;
    color: #fff;
    font-size: 2px;
    background-image: url("../assets/car.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

.switch {
    position: absolute;
    top: 50px;
    left: 20px;
    background: #fff;
    padding: 20px;
    box-sizing: border-box;
}
</style>
<script setup>
import * as THREE from 'three';


import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import TWEEN from '@tweenjs/tween.js';
import { computed, onMounted, ref } from 'vue';

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import Stats from 'three/examples/jsm/libs/stats.module.js';
import { CSS3DRenderer, CSS3DSprite } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { OutlinePass } from 'three/examples/jsm/postprocessing/OutlinePass.js';
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
import {CSS2DRenderer, CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
const dglist = ref(['1', '2', '3', '4', '5', '6', '7', '8'])

const list = ref([

    {
        label: "01",
        name: "GZ001",
        value: false
    },
    {
        label: "02",
        name: "GZ002",
        value: false
    },
    {
        label: "03",
        name: "GZ003",
        value: false
    },
    {
        label: "04",
        name: "GZ004",
        value: false
    },
    {
        label: "05",
        name: "GZ005",
        value: false
    },
    {
        label: "06",
        name: "GZ006",
        value: false
    },
    {
        label: "07",
        name: "GZ007",
        value: false
    },
    {
        label: "08",
        name: "GZ008",
        value: false
    },
])
const stats = new Stats();
document.body.appendChild(stats.domElement);
const scene = new THREE.Scene();
const width = window.innerWidth;
const height = window.innerHeight;
const loader = new GLTFLoader();
// const dracoLoader=new DRACOLoader();
// dracoLoader.setDecoderPath('./libs/dracogltf/')
// loader.setDRACOLoader(dracoLoader)
const textureCube = new THREE.CubeTextureLoader().setPath("./envMap/").load(['px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg'])
const loaderr = () => {
    loader.load("./收费站.glb", e => {
        console.log(e, "收费站")

        e.scene.traverse(el => {

            if (el.isMesh) {
                el.material.envMap = textureCube
                // el.material.envMapIntensity = 10.0

            }
        })
        scene.add(e.scene)
        for (var i = 0; i < dglist.value.length; i++) {
            let div = document.getElementById("tag").cloneNode();

            div.innerHTML = "CD0" + dglist.value[i]
            console.log("dfiv")
            const tag = new CSS3DSprite(div);

            // tag.scale.set(0.05,0.05,1)
            div.style.pointerEvents = "none";
            const obj = scene.getObjectByName("CD0" + dglist.value[i]);
            console.log(obj, "obj")
            tag.position.y += 0.5
            obj.add(tag)

        }
        for (var j = 0; j < dglist.value.length; j++) {
            let imgtexture = new THREE.TextureLoader();
            let imtexture = null;
            imtexture = imgtexture.load("./光点.png")
            let spiriteMaterial = new THREE.SpriteMaterial({
                map: imtexture,
                transparent: true,
                color: 0x00ffff
            })
            let spirit = new THREE.Sprite(spiriteMaterial);
            spirit.name = "";
            spirit.name = "GZ00" + dglist.value[j];
            console.log(spirit.name, "spirit.name")
            const obj = scene.getObjectByName("GZ00" + dglist.value[j]);
            const box3 = new THREE.Box3();
            box3.expandByObject(obj)
            const size = new THREE.Vector3();
            box3.getSize(size);
            spirit.position.x += size.x * 0.7

            obj.add(spirit)
        }

        const objk = scene.getObjectByName("收费窗口");
        console.log(objk, "objk")
        objk.children.forEach(el => {
            el.children.forEach(ell => {
                ell.biaoshi = el.name
            })
        })


    })
    // outlinePass.selectedObjects=[scene.getObjectByName("CD00"),scene.getObjectByName("CD01")]
}



// scene.environment=textureCube
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
var a = new THREE.Vector3(1, 1, 1);
camera.position.set(0, 10, 100)
camera.lookAt(0, 0, 0)
// OutlinePass第一个参数v2的尺寸和canvas画布保持一致
const v2 = new THREE.Vector2(window.innerWidth, window.innerHeight);
// const v2 = new THREE.Vector2(800, 600);
const outlinePass = new OutlinePass(v2, scene, camera);
//模型描边颜色，默认白色         
outlinePass.visibleEdgeColor.set(0x00ffff);
//高亮发光描边厚度
outlinePass.edgeThickness = 4;
//高亮描边发光强度
outlinePass.edgeStrength = 6;
//模型闪烁频率控制，默认0不闪烁
outlinePass.pulsePeriod = 2;
const axesHelper = new THREE.AxesHelper(150);
scene.add(axesHelper);
const skytextureload = new THREE.TextureLoader();
const skytexture = skytextureload.load("./全景2048.jpg")

const geometry1 = new THREE.SphereGeometry(200, 32, 16);
const material1 = new THREE.MeshBasicMaterial({
    map: skytexture,
    side: THREE.BackSide
});
const sphere = new THREE.Mesh(geometry1, material1);
scene.add(sphere);
const directionalLight = new THREE.AmbientLight(0xffffff, 0.5);
// 设置光源的方向：通过光源position属性和目标指向对象的position属性计算
directionalLight.position.set(200, 200, 200);
// directionalLight.intensity=12
scene.add(directionalLight);
// const dirLightHelper = new THREE.DirectionalLightHelper(directionalLight, 5,0xff0000);
// scene.add(dirLightHelper);
const render = new THREE.WebGLRenderer({
    logarithmicDepthBuffer: true,
    antialias: true
});
render.setSize(width, height)
const css2render = new CSS2DRenderer();
      css2render.setSize(window.innerWidth, window.innerHeight);

      css2render.domElement.style.position = "absolute";
      css2render.domElement.style.top = "0px";
      css2render.domElement.style.pointerEvents = "none";
const css3Renderer = new CSS3DRenderer();
css3Renderer.setSize(window.innerWidth, window.innerHeight);
css3Renderer.domElement.style.position = "absolute"
css3Renderer.domElement.style.top = "0px"
css3Renderer.domElement.style.pointerEvents = "none"

const composer = new EffectComposer(render);
// 创建一个渲染器通道，场景和相机作为参数
const renderPass = new RenderPass(scene, camera);

composer.addPass(renderPass)
composer.addPass(outlinePass)
window.addEventListener("resize", () => {
    css3Renderer.setSize(window.innerWidth, window.innerHeight)
    render.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix()
})
const intersectObject = ref(null);
let chooseguo = null;
let namee = ""
let choose = null;
const close=()=>{
    let div = document.getElementById("message").cloneNode();

    console.log("dfiv")
    const tag = new CSS3DSprite(div);

    if (choose) {
        console.log(123)
        choose.remove(tag)
    }

}
render.domElement.addEventListener("click", e => {
    let div = document.getElementById("message").cloneNode();

    console.log("dfiv")
    const tag = new CSS3DSprite(div);
    if (choose) {
        console.log(123)
        choose.remove(tag)
    }

    const px = e.offsetX;
    const py = e.offsetY;
    const x = (px / window.innerWidth) * 2 - 1;
    const y = -(py / window.innerHeight) * 2 + 1;
    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(new THREE.Vector2(x, y), camera);
    intersectObject.value = raycaster.intersectObjects(scene.children);

    console.log(intersectObject.value[0], "intersectObject.value[0]")

    if (intersectObject.value[0].object.biaoshi) {
        let chossarr = scene.getObjectByName("收费窗口");
        intersectObject.value = raycaster.intersectObjects(chossarr.children, true);

        console.log(chossarr.children, "chossarr.children")
        for (let i = 0; i < chossarr.children.length; i++) {

            const group = chossarr.children[i]
            group.traverse(obj => {
                obj.ancastors = group
            })
        }
        console.log(intersectObject.value[0].object.ancastors, "value")
        if (intersectObject.value.length > 0) {
            choose = intersectObject.value[0].object.ancastors

        } else {


        }

        if (choose) {

            outlinePass.selectedObjects = [choose]
            console.log(outlinePass.selectedObjects)
        } else {
            // choose = null
        }
        const A = scene.getObjectByName(intersectObject.value[0].object.ancastors.name);
        console.log(A, "A")
        const pos = new THREE.Vector3();
        A.getWorldPosition(pos);
        const pos2 = pos.clone().addScalar(0, 10, 100)
        new TWEEN.Tween({
            x: camera.position.x,
            y: camera.position.y,
            z: camera.position.z,
            tx: 0,
            ty: 0,
            tz: 0,
        }).to({
            x: pos2.x,
            y: pos2.y,
            z: pos2.z,
            tx: pos2.x,
            ty: pos2.y,
            tz: pos2.z
        }, 2000).onUpdate((obj) => {
            camera.lookAt(obj.tx, obj.ty, obj.tz)

        }).start()


        // obj.remove(tag)
        // tag.scale.set(0.05,0.05,1)
        div.style.pointerEvents = "none";
        const obj = scene.getObjectByName(intersectObject.value[0].object.ancastors.name);
        console.log(obj, "obj")
        div.innerHTML="收费窗口"+intersectObject.value[0].object.ancastors.name
        tag.position.y += 5
        if (chooseguo !== null) {
            console.log("choose")


        }
        choose.add(tag)

    setTimeout(()=>{
choose.remove(tag)
new TWEEN.Tween({
    x: pos2.x,
            y: pos2.y,
            z: pos2.z,
            tx: pos2.x,
            ty: pos2.y,
            tz: pos2.z,
               
        }).to({
            x: 0,
            y: 10,
            z: 100,
            tx: 0,
            ty: 0,
            tz: 0,
    
             }, 2000).onUpdate((obj) => {
            camera.lookAt(obj.tx, obj.ty, obj.tz)

        }).start()

    },5000)
        chooseguo = "1"

    } else {
        intersectObject.value = raycaster.intersectObjects(scene.children);
        namee = intersectObject.value[0].object.name

        langanjh()

    }



})

const changeswitch = (e) => {
    console.log(e, "eee")
    console.log(list.value[e])
    namee = list.value[e].name;
    langanjh()
}
const langanjh = () => {

    console.log(namee, "name")

    let obj = scene.getObjectByName(namee);
    console.log(obj, "obj")
    obj.children.forEach(el => {
        // obj.isopen=false
        if (el.isMesh) {
            console.log(namee, "name", el.isopen)
            if (namee == 'GZ001' || namee == 'GZ002' || namee == 'GZ003') {
                console.log("11")
                if (!el.isopen || el.isopen == false) {
                    el.isopen = true
                    let obj = {
                        angle: Math.PI / 2
                    }
                    const tween = new TWEEN.Tween(obj);
                    tween.to({ angle: Math.PI }, 2000);
                    tween.onUpdate(() => {
                        el.rotation.z = obj.angle
                    })
                    tween.start();
                    // el.rotateZ(45)
                } else {
                    console.log("22")
                    el.isopen = false
                    let obj = {
                        angle: Math.PI
                    }
                    const tween = new TWEEN.Tween(obj);
                    tween.to({ angle: Math.PI / 2 }, 2000);
                    tween.onUpdate(() => {
                        el.rotation.z = obj.angle
                    })
                    tween.start();
                }
            } else if (namee == 'GZ004') {
                if (!el.isopen || el.isopen == false) {
                    console.log("333")
                    el.isopen = true

                    //原始位置
                    let obj = {
                        angle: Math.PI / 2
                    }
                    const tween = new TWEEN.Tween(obj);
                    //目标位置
                    tween.to({ angle: 0 }, 2000);
                    tween.onUpdate(() => {
                        el.rotation.z = obj.angle
                    })
                    tween.start();
                    // el.rotateZ(-45)
                } else {
                    console.log("444")
                    el.isopen = false
                    let obj = {
                        angle: 0
                    }
                    const tween = new TWEEN.Tween(obj);
                    tween.to({ angle: Math.PI / 2 }, 2000);
                    tween.onUpdate(() => {
                        el.rotation.z = obj.angle
                    })
                    tween.start();
                }
            } else {
                if (!el.isopen || el.isopen == false) {
                    console.log("33")
                    el.isopen = true
                    let obj = {
                        angle: Math.PI / 2
                    }
                    const tween = new TWEEN.Tween(obj);
                    //目标位置
                    tween.to({ angle: Math.PI }, 2000);
                    tween.onUpdate(() => {
                        el.rotation.z = obj.angle
                    })
                    tween.start();

                } else {
                    console.log("44")
                    el.isopen = false
                    let obj = {
                        angle: Math.PI
                    }
                    const tween = new TWEEN.Tween(obj);
                    //目标位置
                    tween.to({ angle: Math.PI / 2 }, 2000);
                    tween.onUpdate(() => {
                        el.rotation.z = obj.angle
                    })
                    tween.start();

                }
            }

            let index = list.value.findIndex(item => item.name == namee);
            list.value[index].value = el.isopen


        }
    })
}


const setrender = () => {
    stats.update()
    css3Renderer.render(scene, camera)
    composer.render();
    // render.render(scene, camera); //执行渲染操作
    TWEEN.update();
    window.requestAnimationFrame(setrender);
}
setrender()

const controls = new OrbitControls(camera, render.domElement)
controls.addEventListener('change', e => {

    render.render(scene, camera)
})
// const appp=document.getElementById("gobal")
onMounted(() => {
    console.log(document.getElementById("gobal"), "document.getElementById")
    document.getElementById("gobal").appendChild(render.domElement)
    document.getElementById("gobal").appendChild(css3Renderer.domElement)
    document.getElementById("gobal").appendChild(css2render.domElement);
    loaderr()

})


</script>
<style>
.appp {
    width: 100%;
    height: 100%;
}
</style>